package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1906. 查询差绝对值的最小值
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/11 17:25
 */
public class MinDifference2 {

    public int[] minDifference(int[] nums, int[][] queries) {
        int length = nums.length;
        int[][] arr = new int[length][101];
        int[] items = new int[101];
        for (int i = 0; i < length; i++) {
            items[nums[i]]++;
            arr[i] = items.clone();
        }
        int n = queries.length;
        int[] res = new int[n];
        Arrays.fill(res, 105);
        for (int i = 0; i < n; i++) {
            int l = queries[i][0];
            int r = queries[i][1];
            Arrays.fill(items, 0);
            int pre = 0;
            items[nums[l]]++;
            for (int j = 0; j < 101; j++) {
                items[j] += arr[r][j] - arr[l][j];
                if (items[j] > 0) {
                    if (pre != 0) {
                        res[i] = Math.min(j - pre, res[i]);
                    }
                    pre = j;
                }
            }
            res[i] = res[i] == 105 ? -1 : res[i];
        }
        return res;
    }

}
